//
//  Launch.m
//  LaunchImageTest
//
//  Created by MTiMac01 on 2017/4/26.
//  Copyright © 2017年 ljl. All rights reserved.
//

#import "Launch.h"
#import "IGLaunchImageApi.h"

@interface Launch ()
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (nonatomic,strong) IGLaunchImageApi *launchImageApi;

@end

static NSString *kLaunchImageUrl = @"launchImageUrl";
@implementation Launch
{
    NSFileManager *manager;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    manager = [NSFileManager defaultManager];
    self.img.image = [UIImage imageNamed:@"LaunchImage"];
//    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:KLanguage];
//
//    BOOL isChinese = NO;
//    if ([language containsString:@"zh-Hans"]) {
//        isChinese = YES;
//    } else isChinese = NO;
//
//    if (isChinese) {
//        self.img.image = [UIImage imageNamed:@"LaunchImage1"];
//    } else {
//        self.img.image = [UIImage imageNamed:@"LaunchImage2"];
//    }
    
    
    
    //展示默认图
    //从沙盒取数据，并判断有无图片
    NSString *path = [self launchImagePath];
    NSArray *files = [manager subpathsOfDirectoryAtPath:path error:nil];

    if(files.count!=0){
        //有图片 随机加载
        int j = arc4random()%files.count;
        self.img.image = [UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",j]]];
    }
    
    //请求接口，获取最新的广告页
    _launchImageApi = [[IGLaunchImageApi alloc]init];
    if ([self isFirstLauch]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60*NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [_launchImageApi startWithDecodeClass:[IGLaunchImageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                if (responseObject) {
                    IGLaunchImageResp *resp = responseObject;
                    IGLaunchImageModel *model = resp.data;
                    NSArray *imageArray = model.lstLaunchPages;
                    //判断是否有更新
                    BOOL isNeedDownloadNewImage = YES;
                    id userdefaultObject = [[NSUserDefaults standardUserDefaults]objectForKey:kLaunchImageUrl];
                    if ([userdefaultObject isKindOfClass:[NSArray class]]) {
                        NSArray *userdefaultArray = (NSArray *)userdefaultObject;
                        if (userdefaultArray.count!=0) {
                            if ([userdefaultArray isEqual:imageArray]) {
                                isNeedDownloadNewImage = NO;
                            }
                        }
                    }
                    if (isNeedDownloadNewImage) {
                        //有更新 下载图片 删除老图片 并存储到沙盒
                        NSString *path = [self launchImagePath];
                        NSMutableArray *imageUrlArray = [NSMutableArray array];
                        for (int i= 0; i<imageArray.count; i++) {
                            @autoreleasepool{
                                NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageArray[i]]];
                                UIImage *image = [[UIImage alloc]initWithData:data];
                                NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",i]];
                                BOOL rslt = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                                if (rslt == YES) {
                                    [imageUrlArray addObject:imageArray[i]];
                                }
                            }
                        }
                        [[NSUserDefaults standardUserDefaults] setObject:imageUrlArray forKey:kLaunchImageUrl];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                    }
                };
            }];
        });
    } else {
        [_launchImageApi startWithDecodeClass:[IGLaunchImageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                IGLaunchImageResp *resp = responseObject;
                IGLaunchImageModel *model = resp.data;
                NSArray *imageArray = model.lstLaunchPages;
                //判断是否有更新
                BOOL isNeedDownloadNewImage = YES;
                id userdefaultObject = [[NSUserDefaults standardUserDefaults]objectForKey:kLaunchImageUrl];
                if ([userdefaultObject isKindOfClass:[NSArray class]]) {
                    NSArray *userdefaultArray = (NSArray *)userdefaultObject;
                    if (userdefaultArray.count!=0) {
                        if ([userdefaultArray isEqual:imageArray]) {
                            isNeedDownloadNewImage = NO;
                        }
                    }
                }
                if (isNeedDownloadNewImage) {
                    //有更新 下载图片 删除老图片 并存储到沙盒
                    NSString *path = [self launchImagePath];
                    NSMutableArray *imageUrlArray = [NSMutableArray array];
                    for (int i= 0; i<imageArray.count; i++) {
                        @autoreleasepool{
                            NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageArray[i]]];
                            UIImage *image = [[UIImage alloc]initWithData:data];
                            NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",i]];
                            BOOL rslt = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                            if (rslt == YES) {
                                [imageUrlArray addObject:imageArray[i]];
                            }
                        }
                    }
                    [[NSUserDefaults standardUserDefaults] setObject:imageUrlArray forKey:kLaunchImageUrl];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                }
            };
        }];
    }
    
}

-(NSString *)launchImagePath{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [document stringByAppendingPathComponent:@"launchImage"];
    BOOL isDir = NO;
    BOOL isExsit = [manager fileExistsAtPath:filePath isDirectory:&isDir];
    if (!(isDir == YES && isExsit == YES)) {
        [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}

- (BOOL)isFirstLauch {
    //获取当前版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentAppVersion = infoDic[@"CFBundleShortVersionString"];
    //获取上次启动应用保存的appVersion
    NSString *version = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
    //版本升级或首次登录
    if (version == nil || ![version isEqualToString:currentAppVersion]) {
        return YES;
    } else {
        return NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
